package com.itfitness.mchart.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.EaseConstant;
import com.hyphenate.easeui.domain.EaseUser;
import com.hyphenate.easeui.ui.EaseContactListFragment;
import com.hyphenate.easeui.widget.EaseContactList;
import com.itfitness.mchart.R;
import com.itfitness.mchart.activity.ChartActivity;
import com.itfitness.mchart.activity.GroupActivity;
import com.itfitness.mchart.activity.InvitenotifyActivity;
import com.itfitness.mchart.constant.Constant;
import com.itfitness.mchart.factory.DialogFactory;
import com.itfitness.mchart.utils.ListUtil;
import com.itfitness.mchart.widget.ContactItemView;

import java.util.List;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * @ProjectName: MChart
 * @Package: com.itfitness.mchart.fragment
 * @ClassName: ContactListFragment
 * @Description: java类作用描述 ：联系人列表页面
 * @Author: 作者名：lml
 * @CreateDate: 2019/4/24 9:30
 * @UpdateUser: 更新者：
 * @UpdateDate: 2019/4/24 9:30
 * @UpdateRemark: 更新说明：
 * @Version: 1.0
 */

public class ContactListFragment extends EaseContactListFragment implements EaseContactListFragment.EaseContactListItemClickListener {
    private ContactItemView applicationItem;
    private LocalBroadcastManager mLocalBroadcastManager;
    @Override
    protected void initView() {
        super.initView();
        registBroadcast();
        hideTitleBar();
        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.view_contactlistheader, null);
        HeaderItemClickListener clickListener = new HeaderItemClickListener();
        applicationItem = (ContactItemView) headerView.findViewById(R.id.application_item);
        if(SPUtils.getInstance().getBoolean(Constant.SP_FLAGINVITENOTIFY,false)){
            applicationItem.showUnreadMsgView();
        }else {
            applicationItem.hideUnreadMsgView();
        }
        applicationItem.setOnClickListener(clickListener);
        headerView.findViewById(R.id.group_item).setOnClickListener(clickListener);
        listView.addHeaderView(headerView);
        initContactList();
        setContactListItemClickListener(this);//设置联系人点击事件
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                final EaseUser user = (EaseUser)listView.getItemAtPosition(position);
                DialogFactory.createDefaultDialog(getContext(), "是否删除该好友？", "确定", "取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        deleteContact(user.getUsername());
                    }
                }, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                }).show();
                return false;
            }
        });
    }

    /**
     * 删除好友
     * @param username
     */
    private void deleteContact(final String username) {
        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                EMClient.getInstance().contactManager().deleteContact(username);
                emitter.onNext(1);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Integer>() {
                    @Override
                    public void accept(Integer integer) throws Exception {
                        if (integer == 1) {
                            ToastUtils.showShort("删除好友成功");
                            initContactList();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("注册", throwable.getMessage());
                        ToastUtils.showShort("删除好友失败，请重试");
                    }
                });
    }

    /**
     * 加载联系人列表
     */
    private void initContactList() {
        Observable.create(new ObservableOnSubscribe<List<String>>() {
            @Override
            public void subscribe(ObservableEmitter<List<String>> emitter) throws Exception {
                List<String> allContactsFromServer = EMClient.getInstance().contactManager().getAllContactsFromServer();
                emitter.onNext(allContactsFromServer);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<List<String>>() {
                    @Override
                    public void accept(List<String> allContactsFromServer) throws Exception {
                        if (allContactsFromServer != null) {
                            Map<String, EaseUser> contactList = ListUtil.getContactList(allContactsFromServer);
                            setContactsMap(contactList);
                            refresh();
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        LogUtils.eTag("获取联系人", throwable.getMessage());
                        ToastUtils.showShort("获取联系人失败");
                    }
                });
    }

    private void registBroadcast() {
        if(mLocalBroadcastManager == null){
            mLocalBroadcastManager = LocalBroadcastManager.getInstance(getContext());
        }
        mLocalBroadcastManager.registerReceiver(new InviteNotifyBroadcastReceiver(),new IntentFilter(Constant.ACTION_INVITENOTIFY));
        mLocalBroadcastManager.registerReceiver(new InviteNotifyBroadcastReceiver(),new IntentFilter(Constant.ACTION_CONTACTCHANGE));
    }
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser){
            if(SPUtils.getInstance().getBoolean(Constant.SP_FLAGINVITENOTIFY,false)){
                applicationItem.showUnreadMsgView();
            }else {
                applicationItem.hideUnreadMsgView();
            }
        }
    }

    @Override
    public void onListItemClicked(EaseUser user) {
        Intent intent = new Intent(getContext(), ChartActivity.class);
        intent.putExtra(EaseConstant.EXTRA_USER_ID,user.getUsername());
        startActivity(intent);
    }

    private class HeaderItemClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.application_item:
                    // 进入申请与通知页面
                    SPUtils.getInstance().put(Constant.SP_FLAGINVITENOTIFY,false);
                    applicationItem.hideUnreadMsgView();
                    startActivity(new Intent(getContext(), InvitenotifyActivity.class));
                    break;
                case R.id.group_item:
                    // 进入群聊列表页面
                    startActivity(new Intent(getContext(), GroupActivity.class));
                    break;
                default:
                    break;
            }
        }

    }
    private class InviteNotifyBroadcastReceiver extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(Constant.ACTION_INVITENOTIFY)){
                applicationItem.showUnreadMsgView();
            }else if(intent.getAction().equals(Constant.ACTION_CONTACTCHANGE)){
                initContactList();
            }
        }
    }
}
